package com.wakala.employment.fragment.finder;

import static com.xuexiang.xui.utils.XToastUtils.toast;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.hjq.toast.Toaster;
import com.kongzue.dialogx.dialogs.MessageDialog;
import com.kongzue.dialogx.dialogs.PopTip;
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener;
import com.leaf.library.StatusBarUtil;
import com.tamsiree.rxkit.RxTool;
import com.tamsiree.rxkit.interfaces.OnSimpleListener;
import com.wakala.employment.R;
import com.wakala.employment.adapter.bean.JobInfoPage;
import com.wakala.employment.adapter.entity.JobInfoVo;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.bean.EventKey;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.databinding.FragmentJobDetailBinding;
import com.wakala.employment.fragment.recruit.RecruitIssueFragment;
import com.wakala.employment.http.TestApi;
import com.wakala.employment.utils.Desensitization;
import com.xuexiang.rxutil2.rxbus.RxBusUtils;
import com.xuexiang.xaop.annotation.SingleClick;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xhttp2.model.ApiResult;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xpage.utils.GsonUtils;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.tip.ToastUtils;
import com.yechaoa.yutils.YUtils;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link JobDetailFragment#} factory method to
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none)
public class JobDetailFragment extends BaseFragment<FragmentJobDetailBinding> implements View.OnClickListener {

    public static final String TAG = JobDetailFragment.class.getSimpleName();

    private Long jobInfoId;
    private JobInfoVo mJobInfoVo;

    //---高德地图
    private AMap aMap;
    private MapView mapView;
    //public AMapLocationClient mLocationClient = null;
    //public AMapLocationClientOption mLocationOption = null;
    //--高德地图


    @NonNull
    @Override
    protected FragmentJobDetailBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentJobDetailBinding.inflate(inflater, container, attachToRoot);
    }

    @Override
    protected TitleBar initTitle() {
        TitleBar titleBar = super.initTitle();
        titleBar.setTitle("职位详情");
        titleBar.setTitleColor(R.color.black);
        titleBar.setLeftTextColor(R.color.black);
        titleBar.setLeftImageDrawable(getResources().getDrawable(R.drawable.icon_arrow_back));
        titleBar.setBackgroundResource(R.color.white);//设置标题栏背景颜色
        StatusBarUtil.setDarkMode(getActivity());
        titleBar.addAction(new TitleBar.ImageAction(R.drawable.icon_share) {
            @Override
            @SingleClick
            public void performAction(View view) {
                toast("点击了分享");
            }

            @Override
            public int rightPadding() {
                return DensityUtils.dp2px(getContext(), 10);
            }
        });
        //设置状态栏背景颜色，如果设置为 Color.TRANSPARENT 将会隐藏状态栏
        getActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.white));
        return titleBar;
    }


    @Override
    protected void initArgs() {
        super.initArgs();
        assert getArguments() != null;
        jobInfoId = getArguments().getLong("jobInfoId");
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        //初始化高德地图组件
        mapView = view.findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        return view;
    }

    //画定位标记图
    public void drawMarkers(double latitude, double longitude) {
        //
        CameraPosition cameraPosition = new CameraPosition(new LatLng(latitude, longitude), 15, 0, 30);
        //CameraPosition cameraPosition = new CameraPosition(centerSHpoint, 15, 0, 30);
        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
        aMap.moveCamera(cameraUpdate);
        //
        MarkerOptions markerOptions = new MarkerOptions()
                .position(new LatLng(latitude, longitude))
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_dingwei))
                .draggable(true);
        Marker marker = aMap.addMarker(markerOptions);
        marker.showInfoWindow();
    }

    @Override
    protected void initViews() {

    }

    @Override
    protected void initListeners() {
        super.initListeners();
        binding.sbCloseJob.setOnClickListener(view -> handlerItemCloseClick());
        binding.sbEditJob.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(null!=mJobInfoVo){
                    openNewPage(RecruitIssueFragment.class,"edit-data",mJobInfoVo);
                }else {
                    Toaster.show("当前招聘信息不存在");
                }

            }
        });
        //加载职位数据
        getJobInfo();
    }


    @Override
    public void onClick(View view) {

    }


    /**
     * 查询招聘信息详情数据
     *
     * @return
     */
    @SuppressLint("CheckResult")
    private void getJobInfo() {
        appLoadingDialog.show();
        XHttpProxy.proxy(TestApi.IJobService.class)
                .getJobInfoById(jobInfoId)
                .subscribeWith(new NoTipRequestSubscriber<JobInfoVo>() {
                    @Override
                    protected void onSuccess(JobInfoVo jobInfoVo) {
                        Log.i(TAG, "-------------招工信息详情------------------");
                        if (null != jobInfoVo) {
                            mJobInfoVo = jobInfoVo;
                            bindData(jobInfoVo);
                            Log.i(TAG, GsonUtils.toJson(jobInfoVo));
                            Toaster.show("信息列表已刷新");
                            appLoadingDialog.dismiss();
                            //给地图打标记
                            drawMarkers(Double.parseDouble(jobInfoVo.getJobLat()), Double.parseDouble(jobInfoVo.getJobLng()));
                        }
                        Log.i(TAG, "-------------招工信息详情------------------");
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        ToastUtils.toast(e.getDisplayMessage());
                        appLoadingDialog.dismiss();
                        Log.i(TAG, "-------------招工信息详情-返回错误------------------");
                        Log.e(TAG, e.getMessage());
                    }
                });
    }

    /**
     * 招工详情绑定到界面组件
     *
     * @param jobInfoVo
     */
    private void bindData(JobInfoVo jobInfoVo) {
        //头像
        RequestOptions options = new RequestOptions()
                .centerCrop()
                .placeholder(R.color.color_f4)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        Glide.with(binding.ivUserAvatar.getContext()).load(jobInfoVo.getUser().getAvatar())
                .apply(options)
                .into(binding.ivUserAvatar);
        //名称
        binding.tvUserName.setText(jobInfoVo.getUser().getNickname());
        //标题
        if (StringUtils.isEmpty(jobInfoVo.getTitle())) {
            binding.tvTitle.setText(jobInfoVo.getContent());
        }else{
            binding.tvTitle.setText(jobInfoVo.getTitle());
        }
        //招工详情
        binding.tvSummary.setText(Html.fromHtml(jobInfoVo.getContent(), Html.FROM_HTML_MODE_COMPACT));
        //发布(更新)时间
        binding.tvPublishTime.setText(jobInfoVo.getPublishTime().substring(0, 16));
        //所在城市
        binding.tvJobCity.setText(jobInfoVo.getJobUserAddress().getProvince() + jobInfoVo.getJobUserAddress().getCity());
        //详细地址
        binding.tvLocation.setText(jobInfoVo.getJobUserAddress().getProvince() + jobInfoVo.getJobUserAddress().getCity()
                + jobInfoVo.getJobUserAddress().getDistrict() + jobInfoVo.getJobUserAddress().getDetail());
        //jobInfoVo.setLinkPhone(jobInfoVo.getLinkPhone().substring(0,3)+"********");
        binding.btnLinkBoss.setTag(jobInfoVo.getLinkPhone());
        jobInfoVo.setLinkPhone(Desensitization.mobilePhoneDesensitization(jobInfoVo.getLinkPhone()));
        if (jobInfoVo.getUser().getRealNameAuth()) {
            binding.fgIsAuthed.setVisibility(View.VISIBLE);
            binding.tvJobLinkPhone1.setVisibility(View.VISIBLE);
            binding.tvJobLinkPhone2.setVisibility(View.GONE);
            binding.tvJobLinkPhone1.setText(jobInfoVo.getLinkPhone());
        } else {
            binding.fgIsAuthed.setVisibility(View.GONE);
            binding.tvJobLinkPhone1.setVisibility(View.GONE);
            binding.tvJobLinkPhone2.setVisibility(View.VISIBLE);
            binding.tvJobLinkPhone2.setText(jobInfoVo.getLinkPhone());
        }
        if (jobInfoVo.getUser().getEnterpriseAuth()) {
            binding.fgIsAuthedEnterprise.setVisibility(View.VISIBLE);
        } else {
            binding.fgIsAuthedEnterprise.setVisibility(View.GONE);
        }

    }

    /**
     * 去修改招工信息
     */
    private void goEditJobInfo() {
        //修改
    }

    /**
     * 关闭职位
     *
     * @param
     */
    private void handlerItemCloseClick() {

        MessageDialog messageDialog = new MessageDialog("系统提示", "关闭职位后，不会再有工人联系您，确认关闭吗？", "确定", "取消")
                .setButtonOrientation(LinearLayout.VERTICAL);
        messageDialog.setStyle(com.kongzue.dialogx.style.MIUIStyle.style());
        messageDialog.setOkButton(new OnDialogButtonClickListener<MessageDialog>() {
            @Override
            public boolean onClick(MessageDialog messageDialog, View view) {
                //发起请求关闭
                RxTool.delayToDo(1000, new OnSimpleListener() {
                    @Override
                    public void doSomething() {
                        closeJobInfo();
                    }
                });
                return false;
            }
        });
        messageDialog.setCancelButton(new OnDialogButtonClickListener<MessageDialog>() {
            @Override
            public boolean onClick(MessageDialog messageDialog, View view) {
                return false;
            }
        });
        messageDialog.show();
    }

    @SuppressLint("CheckResult")
    private void closeJobInfo() {
        appLoadingDialog.show();
        XHttpProxy.proxy(TestApi.IJobService.class)
                .closeJobInfo(jobInfoId)
                .subscribeWith(new NoTipRequestSubscriber() {
                    @Override
                    protected void onSuccess(Object object) {
                        Log.i(TAG, "-------------关闭招工------------------");
                        appLoadingDialog.dismiss();
                        Toaster.show("招工信息已关闭");
                        RxTool.delayToDo(2000, new OnSimpleListener() {
                            @Override
                            public void doSomething() {
                                popToBack();
                                RxBusUtils.get().postRxEvent(EventKey.EVENT_BACK_NORMAL+"_job_detail");
                            }
                        });

                        Log.i(TAG, "-------------关闭招工------------------");
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        ToastUtils.toast(e.getDisplayMessage());
                        appLoadingDialog.dismiss();
                        Log.i(TAG, "-------------关闭招工-返回错误------------------");
                        Log.e(TAG, e.getMessage());
                    }
                });
    }
}
